﻿using Midi;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace TestApp1
{
    class Program
    {
        static InputDevice inp;
        static OutputDevice outp;
        public static void Main(string[] args)
        {
            try
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("opening devices");
                string launchpadname = ConfigurationManager.AppSettings["launchapddevicename"];
                inp = InputDevice.InstalledDevices.Where(x => x.Name.ToLowerInvariant().Contains(launchpadname)).First();
                outp = OutputDevice.InstalledDevices.Where(x => x.Name.ToLowerInvariant().Contains(launchpadname)).First();
                inp.ControlChange += inp_ControlChange;
                inp.NoteOff += inp_ControlChange;
                inp.NoteOn += inp_ControlChange;
                inp.Open();
                outp.Open();
                inp.StartReceiving(null);
                Console.WriteLine("press enter to quit");
                Console.ReadLine();
            }
            finally
            {
                if (inp != null)
                {
                    inp.StopReceiving();
                    inp.RemoveAllEventHandlers();
                    try
                    {
                        inp.Close();
                    }
                    catch (Exception e)
                    {
                        //TODO:
                    }
                }
                if (outp != null)
                {
                    try
                    {
                        outp.Close();
                    }
                    catch (Exception e)
                    {
                        //TODO:
                    }
                }
            }

        }

        static void inp_ControlChange(ChannelMessage msg)
        {
            outp.SendMessage(msg);
        }
    }
}
